﻿using Beryl.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace Beryl.OrderControllers.DBUpdate
{
    public class OrderUpdate
    {
        private static OrderUpdate instance = null;
        private static readonly object uniqueLock = new object();
        public static OrderUpdate Instance
        {
            get
            {
                lock (uniqueLock)
                {
                    if (instance == null)
                    {
                        instance = new OrderUpdate();
                    }
                }
                return instance;
            }
        }
        public OrderUpdate() { }

        public bool updatePlanOrder(Dictionary<string, Dictionary<string, Dictionary<string, string>>> para, Dictionary<string, List<string>> cSouArr)
        {
            bool ret = true;
            // sql语句
            List<string> sqlArr = new List<string>();
            string sqlString;
            string sqlString1;
            string sqlString2;
            string sqlString3;
            string sqlString4;
            int bt = 0;
            try
            {
                foreach (var cCusNo in para.Keys)
                {
                    foreach (var planOrderNo in para[cCusNo].Keys)
                    {
                        var Num = para[cCusNo][planOrderNo]["Num"];
                        var dPlanQty1 = para[cCusNo][planOrderNo]["dPlanQty1"];//加工需求
                        var Coefficient = para[cCusNo][planOrderNo]["Coefficient"];
                        var putProQty = para[cCusNo][planOrderNo]["putProQty"];
                        var DepNo = para[cCusNo][planOrderNo]["DepNo"];
                        var DepName = para[cCusNo][planOrderNo]["DepName"];
                        var DeliveryDate = para[cCusNo][planOrderNo]["DeliveryDate"];
                        var MatNo = para[cCusNo][planOrderNo]["MatNo"];
                        var cReworkFlag = para[cCusNo][planOrderNo]["cReworkFlag"];
                        var AutoID = para[cCusNo][planOrderNo]["AutoID"];
                        var cCusName = para[cCusNo][planOrderNo]["cCusName"];
                        var MotypeCode = para[cCusNo][planOrderNo]["MotypeCode"];
                        var Description = para[cCusNo][planOrderNo]["Description"];
                        var dProBatch = para[cCusNo][planOrderNo]["dProBatch"];
                        var Today = CommonMethod.Instance.getTimes();

                        sqlString = string.Format(@"INSERT INTO APS_PlanOrder (AutoID,cPOrderNo,cCusName,cCusNo,cStatusNo,cStaUpdateTime,cMatNo,dPlanQty," +
                                "cProductDepNo,cProductDepName,dDeliveryDate,cReworkFlag,MotypeCode,Description,dProBatch,cMakeTime," +
                               "dPlanQty1,Coefficient,putProQty) VALUES ({0},'{1}','{2}','{3}','0020','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}');", int.Parse(AutoID),
                               planOrderNo, cCusName, cCusNo, Today, MatNo, Num, DepNo, DepName, DeliveryDate, cReworkFlag, MotypeCode, Description, dProBatch, Today, dPlanQty1, Coefficient, putProQty);
                        sqlArr.Add(sqlString);
                        bt++;
                        string return_value = "return_value" + bt.ToString();
                        //计算配比同步
                        sqlString1 = string.Format(@"DECLARE @" + return_value + " int EXEC [dbo].[UpdataProductBaseData] @cMatNo = N'{0}' SELECT 'Return Value' = @" + return_value + "; ", MatNo);
                        sqlArr.Add(sqlString1);

                        var cSONoJson = para[cCusNo][planOrderNo]["json"];
                        Newtonsoft.Json.Linq.JArray jArray = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(CommonMethod.Instance.JosnChange(cSONoJson));
                        for(int i = 0; i < jArray.Count; i++)
                        {
                            var cSONo = jArray[i]["cSONo"].ToString();
                            var cParentSONo = para[cCusNo][planOrderNo]["cParentSONo"];
                            var iRowNo = para[cCusNo][planOrderNo]["iRowNo"];
                            var iSOsID = para[cCusNo][planOrderNo]["iSOsID"];
                            var cMatNo = para[cCusNo][planOrderNo]["MatNo"];
                            // 数量
                            var dTotalQty = jArray[i]["dTotalQty"].ToString();
                            var dPlanQty11 = para[cCusNo][planOrderNo]["dPlanQty1"];

                            sqlString2 = string.Format(@"INSERT INTO APS_PlanOandSaleORelat (cPOrderNo,cSourceNo,dPlanQty1,iRowNo,iSOsID,cProductDepNo) VALUES" +
                                " ('{0}','{1}','{2}','{3}','{4}','{5}');", planOrderNo, cSONo, dPlanQty11, iRowNo, iSOsID, DepNo);
                            sqlArr.Add(sqlString2);

                            sqlString3 = string.Format(@"UPDATE APS_SOrder SET cMatNo = '{0}',cSONo = '{1}',cStatusNo = '0020'" +
                               " WHERE cParentSONo = '{2}' AND iRowNo = '{3}';", cMatNo, cSONo, cParentSONo, iRowNo);
                            sqlArr.Add(sqlString3);
                        }
                        foreach (var cParentSONo in cSouArr.Keys)
                        {
                            for (int i = 0; i < cSouArr[cParentSONo].Count; i++)
                            {
                                string iRowNo = cSouArr[cParentSONo][i];
                                sqlString4 = string.Format(@"UPDATE APS_SOrder SET cStatusNo = '0020' WHERE cParentSONo = '{0}' AND iRowNo = '{1}' AND cStatusNo = '0000';", cParentSONo, iRowNo);
                                sqlArr.Add(sqlString4);
                            }
                        }
                    }
                }
                bool ok = CommonMethod.Instance.insertSqlList(sqlArr);
                if (!ok)
                {
                    throw new Exception("插入失败");
                }
            }
            catch (Exception)
            {
                ret = false;
            }
            return ret;
        }

        public bool updateSerialNo(string today, string serialNum, string cProductDepNo)
        {
            bool ret = true;
            try
            {
                string cType = "PG";
                if(cProductDepNo.Equals("Z21"))
                {
                    cType = "P";
                }
                string sqlString = string.Format(@"UPDATE APS_SerialNo SET cDate = '{0}', iSerialNo = {1} WHERE cType = '{2}';", today, serialNum,cType);
                var connstr = SqlHelper.GetConnSting();
                SqlHelper.ExecuteNonQuery(connstr, CommandType.Text, sqlString);
            }
            catch (Exception)
            {
                ret = false;
            }
            return ret;
        }

        public bool updateSONoNetQty(Dictionary<string, Dictionary<string, string>> cSONos)
        {
            string sqlString;
            bool ret = true;
            List<string> listSql = new List<string>();
            try
            {
                foreach (var AutoID in cSONos.Keys)
                {
                    string dNetQty = cSONos[AutoID]["dNetQty"];
                    sqlString = string.Format(@"UPDATE APS_SOrder set dNetQty = '{0}' WHERE AutoID = '{1}';", dNetQty, AutoID);
                    listSql.Add(sqlString);
                }
                bool ok = CommonMethod.Instance.insertSqlList(listSql);
                if (!ok)
                {
                    throw new Exception("插入失败");
                }
            }
            catch (Exception)
            {
                ret = false;
            }
            return ret;
        }
    }
}